<script setup lang="ts">
import type { FieldRule } from '@arco-design/web-vue'
import { Message } from '@arco-design/web-vue'
import { cloneDeep, omit } from 'lodash-es'
import { getNodeDetailApi, updateCdnNodeApi } from '@/apis/modules/cdn'
// import { getApiResolveRegionsListApi } from '@/apis/modules/resolve/area'
// import {
//   getComputeMachineGroupListApi,
//   updateComputeMachineGroupStatusApi,
// } from '@/apis/modules/group.ts'
import { diskOptions, indexSizeOptions } from '@/constants/cdn-node'
import { coverObjectValue, separateNumberAndLetter } from '@/utils/cdn'

interface IEmit {
  (event: 'update:visible', value: boolean): void
  (event: 'update:record', value: string): void
  (event: 'save'): void
}

interface IProps {
  visible: boolean
  record?: string
}

const props = defineProps<IProps>()

const emit = defineEmits<IEmit>()
const originData = ref()
const {
  formRef,
  formData,
  formRules: templateRules,
  diskFileSizeUnit,
  diskIndexSizeUnit,
} = useNodeTemplateConfig({
  name: '',
  cluster_id: '',
  cascade_level: 1,
  enable_resolve: true,
  cascade_port: 8080,
  cascade_ip: '',
})

// 节点数据
const { loading, request: getNodeInfo } = useRequest(getNodeDetailApi, {
  success(res) {
    originData.value = cloneDeep(res)
    coverObjectValue(formData, res!)
    const { value, unit } = separateNumberAndLetter(res!.cache_size!)
    const { value: index_value, unit: index_symbol } = separateNumberAndLetter(
      res!.index_size!,
    )
    formData.cache_size = Number(value)
    formData.index_size = Number(index_value)

    const index = diskOptions.find(item => item.label === unit)?.value as number
    diskFileSizeUnit.value = index ?? 2

    const index_val = diskOptions.find(item => item.label === index_symbol)
      ?.value as number
    diskIndexSizeUnit.value = index_val ?? 2

    formData.cluster_id = res!.cluster_id! ? res!.cluster_id! : ''
    formData.cascade_ip = res!.cascade_ip! ? res!.cascade_ip! : ''
    formData.cascade_port = Number(res.cascade_port ?? 0)
  },
})

const formRules = computed<Record<string, FieldRule[]>>(() => {
  return {
    name: [
      { required: true, message: '请输入节点名称' },
      { min: 4, max: 32, message: '输入长度4-32个字符' },
    ],
    cluster_id: [{ required: true, message: '请选择节点区域' }],
    // cascade_ip: [
    //   {
    //     validator(value, callback) {
    //       if (!value) {
    //         return callback('请选择级联 IP')
    //       }
    //       callback()
    //     }
    //   }
    // ],
    cascade_port: [
      { required: true, message: '请输入级联端口' },
      {
        validator(value, callback) {
          if (Number(value) < 1024 || Number(value) > 65535) {
            return callback('取值范围1024-65535')
          }
          if ([8000, 9000].includes(Number(value))) {
            return callback('端口不能为8000，9000')
          }
          callback()
        },
      },
    ],
    ...templateRules.value,
  }
})

// 区域列表数据
// const { data: regionList, run: getRegions } = useListRequest(
//   getCdnClusterSimpleListApi,
//   {
//     params: { offset: 0, limit: -1 },
//   },
// )
const regionList = ref<LabelValue[]>([])
// 获取集群列表
async function getClusterList() {
  const res = await getCdnClusterSimpleListApi({ limit: 0 })
  const list = res.list ?? []

  regionList.value = list
    .map(item => ({ label: item.name!, value: item.id! }))
    .filter(Boolean)
}

// 节点信息回显
watch(
  () => props.record,
  async () => {
    if (!props.record) {
      return
    }
    await getNodeInfo({ id: props.record })
    // await getRegions()
  },
)

// 保存节点信息
const { request: saveRequest } = useRequest(updateCdnNodeApi)
async function handleSave() {
  const error = await formRef.value?.validate()
  if (error)
    return false
  const symbol = diskOptions.find(
    item => item.value === diskFileSizeUnit.value,
  )?.label

  const index_symbol = indexSizeOptions.find(
    item => item.value === diskIndexSizeUnit.value,
  )?.label

  const data = cloneDeep({
    ...(omit(formData, ['ips', 'ip']) as any),
    id: props.record,
    // 为空为主ip
    cascade_ip: formData.cascade_ip,
    cache_size: `${formData.cache_size}${symbol}`,
    index_size: `${formData.index_size}${index_symbol}`,
  })
  async function fn() {
    await saveRequest(data).then(() => {
      emit('update:visible', false)
      emit('save')
      Message.success('操作成功')
    })
  }
  if (
    data.cache_path !== originData.value?.cache_path
    || data.cache_size !== originData.value?.cache_size
    || data.index_size !== originData.value?.index_size
  ) {
    ModalHelper.error(
      {
        content: '修改缓存路径或磁盘空间需要重启节点，确认继续？',
      },
      fn,
    )
  } else {
    fn()
  }
}
function handleClose() {
  emit('update:visible', false)
  formRef?.value?.resetFields()
}

onMounted(() => {
  getClusterList()
})
</script>

<template>
  <a-drawer
    class="basic-drawer edit-cascade-node-drawer"
    title="节点编辑"
    :visible="visible"
    width="448px"
    :close-on-click-modal="false"
    ok-text="保存"
    :loading="loading"
    @close="handleClose"
    @cancel="emit('update:visible', false)"
    @ok="handleSave"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      class="drawer-form"
      layout="vertical"
    >
      <a-form-item
        label="节点名称"
        field="name"
        required
        asterisk-position="end"
      >
        <a-input
          v-model="formData.name"
          placeholder="请输入节点名称"
          :max-length="32"
          show-word-limit
        />
      </a-form-item>
      <a-form-item
        label="节点集群"
        field="cluster_id"
        required
        asterisk-position="end"
      >
        <a-select
          v-model="formData.cluster_id"
          placeholder="请选择节点集群"
          class="w-full"
        >
          <a-option
            v-for="region in regionList"
            :key="region.value"
            :label="region.label"
            :value="region.value!"
          />
        </a-select>
      </a-form-item>
      <a-form-item
        class="reduce-gap"
        field="cascade_level"
        hide-asterisk
        asterisk-position="end"
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            <span>节点层级</span>
            <a-tooltip
              position="top"
              :show-arrow="false"
            >
              <template #content>
                <div>
                  1. L2 节点负责回源，L1 节点自动从 L2 节点获取源站数据。
                </div>
                <div>2. 如果没有 L2 节点，L1 节点直接向源站请求回源。</div>
              </template>
              <i-icons-question class="question-icon cursor-pointer" />
            </a-tooltip>
          </div>
        </template>
        <a-radio-group v-model="formData.cascade_level">
          <a-radio :value="1">
            L1
          </a-radio>
          <a-radio :value="2">
            L2
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        v-if="formData.cascade_level === 1"
        class="reduce-gap"
        field="enable_resolve"
        required
        label="解析链路"
        hide-asterisk
        asterisk-position="end"
      >
        <a-radio-group v-model="formData.enable_resolve">
          <a-radio :value="true">
            加入
          </a-radio>
          <a-radio :value="false">
            移除
          </a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item
        v-else
        label="级联 IP"
        field="cascade_ip"
        hide-asterisk
        asterisk-position="end"
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            级联 IP
            <a-tooltip
              content="L1 节点回源当前 L2 节点时将会使用该 IP 地址。"
              :show-arrow="false"
              position="top"
            >
              <i-icons-question class="question-icon cursor-pointer" />
            </a-tooltip>
          </div>
        </template>
        <a-select
          v-model="formData.cascade_ip"
          placeholder="请选择级联 IP"
          class="w-full"
        >
          <a-option
            label="使用主 IP"
            value=""
          />
          <a-option
            v-for="(ip, i) in formData.ips"
            :key="i"
            :label="ip"
            :value="ip"
          />
        </a-select>
      </a-form-item>
      <a-form-item
        v-if="formData.cascade_level === 2"
        label="级联端口"
        field="cascade_port"
        hide-asterisk
        asterisk-position="end"
        class="!mb-6"
        required
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            <span>级联端口</span>
            <a-tooltip
              position="top"
              :content-style="{ 'max-width': '380px' }"
              :show-arrow="false"
            >
              <template #content>
                <div>L1 节点回源当前 L2 节点时将会使用该端口,不能为8888</div>
              </template>
              <i-icons-question class="question-icon cursor-pointer" />
            </a-tooltip>
          </div>
        </template>
        <a-input-number
          v-model.number="formData.cascade_port"
          hide-button
          :max="65535"
          :precision="0"
          placeholder="请输入级联端口"
        />
      </a-form-item>
      <a-form-item
        label="文件缓存路径"
        field="cache_path"
        required
        hide-asterisk
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            <span>缓存目录</span>
            <span class="text-[#FA5566]">*</span>
            <a-tooltip
              :content-style="{ 'max-width': '509px' }"
              :show-arrow="false"
            >
              <template #content>
                <span>缓存路径请勿设置在 /opt/cdn
                  目录下，否则将造成程序更新异常。</span>
              </template>
              <i-icons-question class="question-icon cursor-pointer" />
            </a-tooltip>
          </div>
        </template>
        <div class="w-full">
          <a-input
            v-model="formData.cache_path"
            placeholder="请输入文件缓存路径"
            :max-length="2048"
            @input="val => (formData.cache_path = val.replace(/\s/g, ''))"
          />
          <div class="mb-2 mt-1 text-xs text-[#86909C]">
            请确保目录已存在
          </div>
        </div>
      </a-form-item>
      <a-form-item
        label="缓存索引容量"
        field="index_size"
        asterisk-position="end"
        validate-trigger="blur"
        hide-asterisk
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            <span>缓存索引容量</span>
            <span class="text-[#FA5566]">*</span>
            <a-tooltip
              :content-style="{ 'max-width': '509px' }"
              :show-arrow="false"
            >
              <i-icons-question class="question-icon" />
              <template #content>
                <span>缓存索引可使用的最大内存，请根据服务器可用内存合理分配大小。</span>
              </template>
            </a-tooltip>
          </div>
        </template>
        <a-input-number
          v-model="formData.index_size"
          :controls="true"
          :precision="0"
          :min="1"
          :max-length="13"
          class="cloud-input-number"
          hide-button
          placeholder="请输入缓存索引容量"
        >
          <template #append>
            <a-select
              v-model="diskIndexSizeUnit"
              :options="indexSizeOptions"
              class="rounded-tl-none rounded-bl-none! border-none! bg-transparent!"
            />
          </template>
        </a-input-number>
      </a-form-item>

      <a-form-item
        label="缓存最大容量"
        field="cache_size"
        hide-asterisk
        asterisk-position="end"
        required
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            <span>缓存最大容量</span>
            <span class="text-[#FA5566]">*</span>
            <a-tooltip
              :content-style="{ 'max-width': '509px' }"
              :show-arrow="false"
            >
              <i-icons-question class="question-icon" />
              <template #content>
                <span>限制磁盘缓存最大容量，超出后自动清理最旧缓存。</span>
              </template>
            </a-tooltip>
          </div>
        </template>
        <a-input-number
          v-model="formData.cache_size"
          :controls="true"
          :precision="0"
          :min="1"
          :max-length="13"
          class="cloud-input-number"
          hide-button
          placeholder="请输入缓存最大容量"
        >
          <template #append>
            <a-select
              v-model="diskFileSizeUnit"
              :options="diskOptions"
              class="rounded-tl-none rounded-bl-none! border-none! bg-transparent!"
            />
          </template>
        </a-input-number>
        <!-- <a-input-number v-model="formData.cache_size" :max-length="13" class="!w-100"  placeholder="请输入缓存最大容量">
            <template #append>
              <a-select v-model="diskFileSizeUnit" :options="diskOptions">
              </a-select>
            </template>
          </a-input-number> -->
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<style scoped lang="less">
.reduce-gap {
  :deep(.arco-form-item-wrapper-col) {
    min-height: 24px;
  }
  :deep(.arco-form-item-content) {
    min-height: 24px;
  }
}

.question-icon {
  color: #86909c;
  width: 14px !important;
  height: 14px !important;
  cursor: pointer;

  &:hover {
    color: #00a65b;
  }
}

:deep(.arco-input-append) {
  background-color: #ffffff;
}
</style>
